package com.moyun.common.utils;

import javax.validation.ConstraintViolation;
import javax.validation.Validation;
import javax.validation.Validator;
import java.util.Collections;
import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;

/**
 * @ClassName ValidateUtil
 * @Description 文档地址: https://juejin.cn/post/7086093314256011294
 * 文档学习地址: https://blog.51cto.com/knifeedge/5251993
 * @Author yangboxuan
 * @Date 2022/6/25 12:03
 */

public class ValidateUtil {

    private static final Validator validatorFactory =
            Validation.buildDefaultValidatorFactory().getValidator();

    /**
     * 校验器
     *
     * @param t   参数
     * @param <T> 参数类型
     * @return
     */
    public static <T> List<String> validate(T t) {
        Set<ConstraintViolation<T>> errors = validatorFactory.validate(t);
        if (!errors.isEmpty()) {
            return errors.stream().map(v -> v.getPropertyPath() + " : " + v.getMessage()).collect(Collectors.toList());
        }
        return Collections.emptyList();
    }

    /**
     * 通过组来校验实体类
     */
    public static <T> List<String> validate(T t, Class<?>... groups) {
        Set<ConstraintViolation<T>> constraintViolations = validatorFactory.validate(t, groups);
        if (!constraintViolations.isEmpty()) {
            return constraintViolations.stream().map(v -> v.getPropertyPath() + " : " + v.getMessage()).collect(Collectors.toList());
        }
        return Collections.emptyList();
    }


}
